package com.chat.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;


/**
 * 将接收到的消息发送给其他channel
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //全局的group
    private static ChannelGroup clients =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                TextWebSocketFrame msg) throws Exception {
        //获得客户端传输过来的消息
        String content = msg.text();
        System.out.println("receive message:" + content);

        //转发给其他channel
        /*for (Channel channel: clients) {
            channel.writeAndFlush(
                    new TextWebSocketFrame("[Server on" +
                            LocalDateTime.now() +"receive message]:" +
                            content));
        }*/
        //和上面的for循环功能一致
        clients.writeAndFlush(
                new TextWebSocketFrame("[Server on" +
                        LocalDateTime.now() +"receive message]:" +
                        content));

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //将此channel放入到全局的channelGroup中，便于发消息
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当客户端关闭后，channelGroup会自动移除对应的channel，效果和下面语句一样
        //clients.remove(ctx.channel());
        System.out.println("A client disconect, channel id: " +
                ctx.channel().id().asLongText());
    }
}
